angular.module('Controller')

.controller('WFMenuManageCtrl', ($scope,NgTableParams,$q,commonUtil,wfAlert,commonConstant,$rootScope,$uibModal,$http) ->
    initSearchData = ()->
        $scope.search = {
            enabled:true
            level:undefined
        }
    $scope.checkbox={
        checked:false
        items:{}
    }
    $scope.checkAll=()->
        _.each $scope.tableData,(data)->
            $scope.checkbox.items[data.id]=$scope.checkbox.checked
    initSearchData()
    $scope.enabledList=commonConstant.enabledList(true)
    $scope.menuLvList=commonConstant.menuLvList(true)
    console.log('menuLvList:',$scope.menuLvList)
    $scope.tableParams = new NgTableParams(
            {page: 1, count: commonConstant.pageTableCount},
            {
                counts: [5, 10, 20],
                getData: ($defer, params)->
                    $scope.doQuery($defer,params)
                    return ;
            }
    )
    $scope.doQuery=($defer, params)->
        requestData={
            page: params.page() - 1,
            size: params.count(),
            enabled: $scope.search.enabled
            moduleNameLike: $scope.search.name
            sort:'sort_no,asc'
        }
        if $scope.search.level==1
            requestData['parent']=0
        getParam=commonUtil.transferGetParam(requestData)
        $http.get('@ostengar/module'+getParam)
        .success (resp)->
            if resp.code==0
                $scope.tableData=resp.message.content
                params.total(resp.message.totalElements)
                $defer.resolve($scope.tableData)
            else
                console.log(resp.message)
        .error (err)->
            console.log(err)
    _.extend $scope,
        newData: ->
            data={name:'',parent:0,enabled:true,level:1,isLeaf:false,sortNo:1}
            showModal('new',data)
        editData:(data)->
            theData=commonUtil.cloneObj(data)
            showModal('edit',theData)
        resetSearch: ->
            initSearchData()
        queryData: (firstPage)->
            if(firstPage == true)
                $scope.tableParams.page(1)
            $scope.tableParams.reload()
        removeData:(id)->
            result=commonUtil.batchRemove('/module/',id,$scope.checkbox.items)
            result.then(((ids)->
                delNum=_.filter(ids,(item)->item.done==true).length
                wfAlert.toastInfo('批量删除完成,共删除'+delNum+'条数据')
                $scope.queryData()
            ),(->angular.noop()))
    showModal=(type,data)->
        $scope.modal = $uibModal.open({
            animation: true,
            appendTo: $("#modalContent:eq(0)"),
            controller: 'WFMenuManageEditCtrl',
            templateUrl: 'templates/system/menu/menu-manage-modal.html',
            resolve: {
                items:  ()->{type: type, data: data}
            }
        })
        $scope.modal.result.then((modalData)->
            $scope.queryData()
        )
)
